package com.lujianfei.mqtt.chat

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.lujianfei.mqtt.common.BindingViewHolder
import com.lujianfei.mqtt.databinding.MsgLeftItemBinding
import com.lujianfei.mqtt.databinding.MsgRightItemBinding

/**
 * @Author: wn
 * @Date: 2024/4/18 9:52
 * @Description: TODO
 */
class MsgAdapter(private val msgList: List<Msg>) : RecyclerView.Adapter<BindingViewHolder>() {

  override fun getItemCount() = msgList.size

  // 获取当前 视图项的 数据源的 类型
  override fun getItemViewType(position: Int): Int {
    return msgList[position].type
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingViewHolder =
    if (viewType == Msg.TYPE_RECEIVED) {
      val binding = MsgLeftItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
      BindingViewHolder(binding)
    } else {
      val binding = MsgRightItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
      BindingViewHolder(binding)
    }

  override fun onBindViewHolder(holder: BindingViewHolder, position: Int) {
    val msg = msgList[position]
    when (holder.binding) {
      is MsgLeftItemBinding -> holder.binding.msg = msg
      is MsgRightItemBinding -> holder.binding.msg = msg
      else -> throw IllegalAccessException()
    }
  }
}